import axios from 'axios'
import {Message} from 'element-ui'

//axios 实例化
const service = axios.create({
    baseURL: "/wecs",
    withCredentials: true,
    timeout: 6000
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        if (!config.url.endsWith("/register")) {
            config.headers['Authorization'] = "bearer " + localStorage.getItem("token");
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    /**
     * 所有返回的数据需要统一格式（获取token的接口）
     * @param response
     * @returns {*}
     */
    response => {
        if (response.status === 200) {
            const res = response.data
            // 检查自定义的响应码
            if (res.code !== 2000) {
                Message({
                    message: res.message || '未知错误',
                    type: 'error',
                    duration: 5 * 1000
                })
                return Promise.reject(new Error(res.message || '未知错误'))
            } else {
                return res
            }
        } else {
            localStorage.removeItem("token");
            // return Promise.reject(new Error('未知错误'))
        }
    },
    error => {
        // console.log('err' + error) // for debug
        //移除登陆凭证，让路由自动拦截跳转到登录页面，暂不提供token刷新功能
        localStorage.removeItem("token");
        Message({
            message: "server：" + error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default service
